package model

import (
	"apiserver/constvar"
	"fmt"
)

type PostModel struct {
	BaseModel
	Title   string `json:"title" gorm:"column:title;not null" binding:"required" validate:"min=10,max=120"`
	Content string `json:"content" gorm:"column:content;not null" binding:"required" validate:"min=10"`
	UserId  uint64 `json:"userId" gorm:"column:userId;not null" sql:"index"`
}

func (c *PostModel) TableName() string {
	return "tb_posts"
}
func (c *PostModel) Create() error {
	return DB.Self.Create(&c).Error
}
func GetPostDetail(pid uint64) (*PostModel, error) {
	p := &PostModel{}
	e := DB.Self.Where("id=?", pid).First(&p)
	return p, e.Error
}
func DeletePost(pid uint64) error {
	p := &PostModel{}
	p.BaseModel.Id = pid
	return DB.Self.Delete(&p).Error
}
func GetPostList(userId uint64, offset, limit int) ([]*PostModel, uint64, error) {
	if limit == 0 {
		limit = constvar.DefaultPostLimit
	}
	posts := make([]*PostModel, 0)
	var count uint64
	where := "1=1"
	if userId > 0 {
		where = fmt.Sprintf("userId = %d", userId)
	}

	if err := DB.Self.Model(&PostModel{}).Where(where).Count(&count).Error; err != nil {
		return posts, count, err
	}
	if err := DB.Self.Where(where).Offset((offset - 1) * limit).Limit(limit).Order("createdAt desc").Find(&posts).Error; err != nil {
		return posts, count, err
	}
	return posts, count, nil
}
